package com.yuanchu.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.common.exception.BizCodeEnum;
import com.yuanchu.common.exception.YuanChuException;
import com.yuanchu.common.utils.PageUtils;
import com.yuanchu.goods.client.FeignStoreClient;
import com.yuanchu.goods.dao.YoshopGoodsCategoryRelDao;
import com.yuanchu.goods.dao.YoshopGoodsDao;
import com.yuanchu.goods.dto.*;
import com.yuanchu.goods.entity.*;
import com.yuanchu.goods.service.*;
import com.yuanchu.goods.utils.FormatUtils;
import com.yuanchu.goods.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.yuanchu.goods.listener.MqGoodsConstants.*;


@Service("yoshopGoodsService")
public class YoshopGoodsServiceImpl extends ServiceImpl<YoshopGoodsDao, YoshopGoodsEntity> implements YoshopGoodsService {

    @Resource
    private YoshopUploadFileService fileService;

    @Resource
    private YoshopGoodsImageService goodsImageService;
    @Resource
    private YoshopGoodsCategoryRelService goodsCategoryRelService;

    @Resource
    private YoshopGoodsService goodsService;
    @Resource
    private YoshopGoodsSkuService goodsSkuService;
    @Resource
    private YoshopSpecService specService;
    @Resource
    private YoshopSpecValueService specValueService;
    @Resource
    private YoshopGoodsSpecRelService goodsSpecRelService;
    @Resource
    private YoshopGoodsCategoryRelDao goodsCategoryRelDao;


    @Resource
    private YoshopGoodsServiceRelService goodsServiceRelService;
    @Resource
    private YoshopUploadFileService yoshopUploadFileService;
    @Resource
    private FeignStoreClient feignStoreClient;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private RabbitTemplate rabbitTemplate;


    @Override
    public PageUtils queryGoodsList(QueryGoodsParamsDto params) {
        // listType: all        显示所有
        // listType: on_sale    出售中(商品状态status(10上架 20下架))
        // listType: off_sale   已下架(商品状态status(10上架 20下架))
        // listType: sold_out   已售完(商品库存总量stockTotal)
        LambdaQueryWrapper<YoshopGoodsEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YoshopGoodsEntity::getIsDelete, 0);
        int categoryId = params.getCategoryId();
        if (categoryId != 0) {
            List<Integer> goodsIds = goodsCategoryRelDao.queryGoodsIdByCategoryId(categoryId);
            lqw.in(!CollectionUtils.isEmpty(goodsIds), YoshopGoodsEntity::getGoodsId, goodsIds);
        }

        String listType = "all";
        if (StringUtils.isNotEmpty(params.getListType())) {
            listType = params.getListType();
        }
        // 根据商品类型查询
        // if ("all".equals(listType)) {
        //     lqw.eq(YoshopGoodsEntity::getIsDelete, 0);
        // } else

        // 根据商品名称查询
        if (StringUtils.isNoneEmpty(params.getGoodsName())) {
            lqw.like(YoshopGoodsEntity::getGoodsName, params.getGoodsName());
        }
        // 根据商品编码查询
        if (StringUtils.isNoneEmpty(params.getGoodsNo())) {
            lqw.eq(YoshopGoodsEntity::getGoodsNo, params.getGoodsNo());
        }
        lqw.orderByAsc(YoshopGoodsEntity::getSort);
        // 分页对象
        Page<YoshopGoodsEntity> page = new Page<>(params.getPage(), params.getPageSize());

        // 获取商品page数据
        IPage<YoshopGoodsEntity> goodsList = this.page(page, lqw);

        List<YoshopGoodsEntity> records = goodsList.getRecords();
        List<QueryGoodsList> list = new ArrayList<>();
        // 获取商品图片
        records.forEach(goods -> {
            QueryGoodsList queryGoods = new QueryGoodsList();
            BeanUtils.copyProperties(goods, queryGoods);
            this.setGoodsImageAndDatetime(queryGoods);
            queryGoods.setContent(null);
            list.add(queryGoods);
        });
        // records.forEach(this::formatDatetime);

        return new PageUtils(list, list.size(), params.getPageSize(), params.getPage());
    }

    public List<YoshopGoodsEntity> queryGoodsALl(QueryGoodsParamsDto params) {
        // listType: all        显示所有
        // listType: on_sale    出售中(商品状态status(10上架 20下架))
        // listType: off_sale   已下架(商品状态status(10上架 20下架))
        // listType: sold_out   已售完(商品库存总量stockTotal)
        LambdaQueryWrapper<YoshopGoodsEntity> lqw = new LambdaQueryWrapper<>();

        int categoryId = params.getCategoryId();
        if (categoryId != 0) {
            List<Integer> goodsIds = goodsCategoryRelDao.queryGoodsIdByCategoryId(categoryId);
            lqw.in(!CollectionUtils.isEmpty(goodsIds), YoshopGoodsEntity::getGoodsId, goodsIds);
        }

        String listType = "all";
        if (StringUtils.isNotEmpty(params.getListType())) {
            listType = params.getListType();
        }
        // 根据商品类型查询
        if ("all".equals(listType)) {
            lqw.eq(YoshopGoodsEntity::getIsDelete, 0);
        } else if ("on_sale".equals(listType)) {
            lqw.eq(YoshopGoodsEntity::getStatus, 10);
        } else if ("off_sale".equals(listType)) {
            lqw.eq(YoshopGoodsEntity::getStatus, 20);
        } else if ("sold_out".equals(listType)) {
            lqw.eq(YoshopGoodsEntity::getStockTotal, 0);
        }
        // 根据商品名称查询
        if (StringUtils.isNoneEmpty(params.getGoodsName())) {
            lqw.like(YoshopGoodsEntity::getGoodsName, params.getGoodsName());
        }
        // 根据商品编码查询
        if (StringUtils.isNoneEmpty(params.getGoodsNo())) {
            lqw.eq(YoshopGoodsEntity::getGoodsNo, params.getGoodsNo());
        }

        // 分页对象
        Page<YoshopGoodsEntity> page = new Page<>(params.getPage(), params.getPageSize());

        // 获取商品page数据
        List<YoshopGoodsEntity> list = this.list(lqw);

        list.forEach(this::formatDatetime);

        return list;
    }


    /**
     * 设置商品图片和时间
     *
     * @param goodsEntity
     */
    private void setGoodsImageAndDatetime(QueryGoodsList goodsEntity) {
        List<YoshopUploadFileEntity> goodsImages = getGoodsImages(goodsEntity.getGoodsId());
        if (CollectionUtils.isEmpty(goodsImages)) {
            return;
        }
        goodsEntity.setGoodsImages(goodsImages);
        goodsEntity.setGoodsImage(goodsImages.get(0).getPreviewUrl());
        formatDatetime(goodsEntity);
    }

    private void formatDatetime(YoshopGoodsEntity goodsEntity) {
        Date createDate = new Date(Long.parseLong(goodsEntity.getCreateTime()) * 1000);
        Date uodateDate = new Date(Long.parseLong(goodsEntity.getUpdateTime()) * 1000);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        goodsEntity.setCreateTime(format.format(createDate));
        goodsEntity.setUpdateTime(format.format(uodateDate));
    }

    @Transactional
    @Override
    public void saveGoodsInfo(AddGoodsParamsDto goodsParams, int storeId) {
        // 1、添加数据到表goods
        Integer goodsId = goodsService.saveGoodsToDb(goodsParams, "", storeId);
        // 2、保存商品规格信息
        goodsService.saveGoodsToSpec(goodsParams, goodsId, storeId);

        // 3、添加商品sku到表goods_sku
        goodsService.saveGoodsToSku(goodsParams, goodsId, storeId);
        // 4、保存商品与分类关系记录表
        goodsService.saveGoodsToCategory(goodsParams.getCategoryIds(), goodsId, storeId);
        // 5、保存商品与图片关系记录表
        goodsService.saveGoodsToImage(goodsParams.getImagesIds(), goodsId, storeId);
        // 6、保存商品与服务记录表
        goodsService.saveGoodsToService(goodsParams.getServiceIds(), goodsId, storeId);

        // 发送消息添加商品到es
        rabbitTemplate.convertAndSend(GOODS_EXCHANGE, GOODS_INSERT_KEY, goodsId);
    }

    @Override
    @Transactional
    public void editById(EditGoodsParamsDto editGoodsParams, int storeId) {
        // 删除缓存
        // 删除所有"goods:detail" 开头的缓存

        // redisUtils.delByPrefix("goods:detail");
        redisUtils.delByPrefix("goods:detail" + editGoodsParams.getGoodsId());
        // 1、修改商品基本信息
        goodsService.saveGoodsToDb(editGoodsParams.getForm(), editGoodsParams.getGoodsId(), storeId);
        // 2、修改商品规格信息
        goodsService.editGoodsToSpec(editGoodsParams, editGoodsParams.getGoodsId(), storeId);
        // 3、修改商品sku到表goods_sku
        goodsService.editGoodsToSku(editGoodsParams.getForm(), editGoodsParams.getGoodsId(), storeId);
        // 4、修改商品与分类关系记录表
        goodsService.editGoodsToCategory(editGoodsParams.getForm().getCategoryIds(), editGoodsParams.getGoodsId(), storeId);
        // 5、修改商品与图片关系记录表
        goodsService.editGoodsToImage(editGoodsParams.getForm().getImagesIds(), editGoodsParams.getGoodsId(), storeId);
        // 6、修改商品与服务记录表
        goodsService.editGoodsToService(editGoodsParams.getForm().getServiceIds(), editGoodsParams.getGoodsId(), storeId);

        // 发送消息添加商品到es
        rabbitTemplate.convertAndSend(GOODS_EXCHANGE, GOODS_INSERT_KEY, editGoodsParams.getGoodsId());

    }

    @Override
    public void editGoodsToSpec(EditGoodsParamsDto editGoodsParams, String goodsId, int storeId) {
        // 删除原来商品规格信息
        goodsSpecRelService.remove(new QueryWrapper<YoshopGoodsSpecRelEntity>().eq("goods_id", goodsId));
        // 添加新的商品规格信息
        this.saveGoodsToSpec(editGoodsParams.getForm(), Integer.valueOf(goodsId), storeId);
    }

    @Override
    public void editGoodsToSku(AddGoodsParamsDto form, String goodsId, int storeId) {
        // 删除原来商品sku信息
        goodsSkuService.remove(new QueryWrapper<YoshopGoodsSkuEntity>().eq("goods_id", goodsId));
        // 添加新的商品规格信息
        this.saveGoodsToSku(form, Integer.valueOf(goodsId), storeId);
    }

    @Override
    public void editGoodsToCategory(List<Integer> categoryIds, String goodsId, int storeId) {
        // 根据categoryIds和goodsId查询是否存在记录，存在
        List<YoshopGoodsCategoryRelEntity> goodsCategoryRel = goodsCategoryRelService.list(new QueryWrapper<YoshopGoodsCategoryRelEntity>().eq("goods_id", goodsId));
        goodsCategoryRel.forEach(entity -> {
            if (!categoryIds.contains(entity.getCategoryId())) {
                // 删除记录
                goodsCategoryRelService.remove(new QueryWrapper<YoshopGoodsCategoryRelEntity>()
                        .eq("goods_id", goodsId).eq("category_id", entity.getCategoryId()));
            } else {
                categoryIds.remove(entity.getCategoryId());
            }
        });
        // 添加新的商品与分类关系记录表
        this.saveGoodsToCategory(categoryIds, Integer.valueOf(goodsId), storeId);
    }

    @Override
    public void editGoodsToImage(List<Integer> imagesIds, String goodsId, int storeId) {
        // 查询原来商品图片信息
        List<YoshopGoodsImageEntity> goodsImageEntityList = goodsImageService.list(new QueryWrapper<YoshopGoodsImageEntity>()
                .eq("goods_id", goodsId).eq("store_id", storeId));
        goodsImageEntityList.forEach(entity -> {
            if (!imagesIds.contains(entity.getImageId())) {
                // 删除记录
                goodsImageService.remove(new QueryWrapper<YoshopGoodsImageEntity>()
                        .eq("goods_id", goodsId).eq("image_id", entity.getImageId()));
            } else {
                imagesIds.remove(entity.getImageId());
            }
        });
        // 添加新的商品与图片关系记录表
        this.saveGoodsToImage(imagesIds, Integer.valueOf(goodsId), storeId);

    }

    @Override
    public void editGoodsToService(List<Integer> serviceIds, String goodsId, int storeId) {
        // 查询原来商品服务信息
        List<YoshopGoodsServiceRelEntity> goodsServiceRel = goodsServiceRelService.list(new QueryWrapper<YoshopGoodsServiceRelEntity>()
                .eq("goods_id", goodsId).eq("store_id", storeId));
        goodsServiceRel.forEach(entity -> {
            if (!serviceIds.contains(entity.getServiceId())) {
                // 删除记录
                goodsServiceRelService.remove(new QueryWrapper<YoshopGoodsServiceRelEntity>()
                        .eq("goods_id", goodsId).eq("service_id", entity.getServiceId()));
            } else {
                serviceIds.remove(entity.getServiceId());
            }
        });
        // 添加新的商品与服务关系记录表
        this.saveGoodsToService(serviceIds, Integer.valueOf(goodsId), storeId);
    }

    @Override
    @Transactional
    public boolean removeGoodsByIds(List<Integer> goodsIds) {
/*         // 1.删除商品基本信息
        goodsService.removeByIds(goodsIds);
        // 2.删除商品关联的规格信息
        goodsSpecRelService.remove(new QueryWrapper<YoshopGoodsSpecRelEntity>().in("goods_id", goodsIds));
        // 3.删除商品关联的sku信息
        goodsSkuService.remove(new QueryWrapper<YoshopGoodsSkuEntity>().in("goods_id", goodsIds));
        // 4.删除商品关联的分类信息
        goodsCategoryRelService.remove(new QueryWrapper<YoshopGoodsCategoryRelEntity>().in("goods_id", goodsIds));
        // 5.删除商品关联的图片信息
        goodsImageService.remove(new QueryWrapper<YoshopGoodsImageEntity>().in("goods_id", goodsIds));
        // 6.删除商品关联的服务信息
        goodsServiceRelService.remove(new QueryWrapper<YoshopGoodsServiceRelEntity>().in("goods_id", goodsIds)); */
        // 修改商品基本信息is_delete字段为1
        goodsService.update(new UpdateWrapper<YoshopGoodsEntity>().in("goods_id", goodsIds).set("is_delete", 1));

        // 删除缓存
        goodsIds.forEach(goodsId -> {
            redisUtils.delByPrefix("goods:detail" + goodsId);
            // 删除es
            // 发送消息删除商品es
            rabbitTemplate.convertAndSend(GOODS_EXCHANGE, GOODS_DELETE_KEY, goodsId);
        });

        return true;
    }

    @Override
    public void updateGoodsState(EditGoodsStateDto params) {
        // 根据id修改商品状态
        params.getGoodsIds().forEach(goodsId -> {
            // 如果state为true，则修改为上架，否则修改为下架
            if (params.isState()) {
                // 商品上架
                boolean flag = goodsService.update(new UpdateWrapper<YoshopGoodsEntity>()
                        .eq("goods_id", goodsId).set("status", 10));
                if (!flag) {
                    throw new YuanChuException(BizCodeEnum.PRODUCT_UP_EXCEPTION.getMsg(), BizCodeEnum.PRODUCT_UP_EXCEPTION.getCode());
                }
                // 删除缓存
                redisUtils.delByPrefix("goods:detail" + goodsId);
                // 发送消息添加商品到es
                rabbitTemplate.convertAndSend(GOODS_EXCHANGE, GOODS_INSERT_KEY, goodsId);
            } else {
                // 商品下架
                boolean flag = goodsService.update(new UpdateWrapper<YoshopGoodsEntity>()
                        .eq("goods_id", goodsId).set("status", 20));
                if (!flag) {
                    throw new YuanChuException(BizCodeEnum.PRODUCT_DOWN_EXCEPTION.getMsg(), BizCodeEnum.PRODUCT_DOWN_EXCEPTION.getCode());
                }
                // 删除缓存
                redisUtils.delByPrefix("goods:detail" + goodsId);
                // 发送消息删除商品es
                rabbitTemplate.convertAndSend(GOODS_EXCHANGE, GOODS_INSERT_KEY, goodsId);
            }

        });


    }

    @Override
    public Integer queryTotalGoods() {
        return this.count(new LambdaQueryWrapper<YoshopGoodsEntity>().eq(YoshopGoodsEntity::getIsDelete, 0));
    }

    @Override
    public long querySoldOutGoodsTotal() {
        return goodsSkuService.count(new QueryWrapper<YoshopGoodsSkuEntity>().eq("stock_num", 0));
    }


    @Override
    public boolean getGoodsByFileIds(List<Long> fileIds) {
        // 如果文件ID列表为空，则直接返回false
        if (CollectionUtils.isEmpty(fileIds)) {
            return false;
        }
        for (Long mediaId : fileIds) {
            List<YoshopGoodsImageEntity> goodsImages = goodsImageService.list(new QueryWrapper<YoshopGoodsImageEntity>().eq("image_id", mediaId));

            // 只要找到一条记录，就立即返回true
            if (!CollectionUtils.isEmpty(goodsImages)) {
                return true;
            }
        }
        // 遍历完所有ID均未找到对应商品图片时返回false
        return false;
    }

    @Override
    public List<YoshopGoodsEntity> queryGoodsByCategoryId(Integer categoryId) {
        LambdaQueryWrapper<YoshopGoodsCategoryRelEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(categoryId != 0, YoshopGoodsCategoryRelEntity::getCategoryId, categoryId);
        lqw.select(YoshopGoodsCategoryRelEntity::getGoodsId);
        List<YoshopGoodsCategoryRelEntity> list = goodsCategoryRelService.list(lqw);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        // 获取商品ids
        List<Integer> goodsIds = list.stream().map(YoshopGoodsCategoryRelEntity::getGoodsId).collect(Collectors.toList());
        LambdaQueryWrapper<YoshopGoodsEntity> goods_lqw = new LambdaQueryWrapper<>();
        goods_lqw.eq(YoshopGoodsEntity::getIsDelete, 0);
        goods_lqw.in(YoshopGoodsEntity::getGoodsId, goodsIds);
        List<YoshopGoodsEntity> goodsEntities = this.list(goods_lqw);
        goodsEntities.forEach(item -> {
            // 默认商品图片
            List<YoshopGoodsImageEntity> imagelist = goodsImageService.list(new QueryWrapper<YoshopGoodsImageEntity>().eq("goods_id", item.getGoodsId()));
            Integer imageId = imagelist.get(0).getImageId();
            item.setGoodsImage(yoshopUploadFileService.getUploadFileById(imageId).getPreviewUrl());
        });
        return goodsEntities;
    }

    @Override
    public YoshopGoodsEntity queryGoodsInfo(Integer goodsId, String goodsSkuId) {

        YoshopGoodsEntity goods = this.getById(goodsId);
        if (goods == null) {
            return null;
        }
        // 获取商品sku信息
        YoshopGoodsSkuEntity goodsSku = goodsSkuService.getOne(new QueryWrapper<YoshopGoodsSkuEntity>()
                .eq("goods_sku_id", goodsSkuId)
                .eq("goods_id", goodsId));
        if (goodsSku == null) {
            return goods;
        }
        // 解析商品规格
        List<Map<String, Object>> goodsProps = goodsSkuService.getGoodsProps(goodsSku.getGoodsProps());
        GoodsSkuDto goodsSkuDto = new GoodsSkuDto();
        BeanUtils.copyProperties(goodsSku, goodsSkuDto);
        goodsSkuDto.setGoodsProps(goodsProps);
        Integer imageId = goodsSku.getImageId();
        if (imageId == null || imageId == 0) {
            // 默认商品图片
            List<YoshopGoodsImageEntity> imagelist = goodsImageService.list(new QueryWrapper<YoshopGoodsImageEntity>().eq("goods_id", goodsId));
            imageId = imagelist.get(0).getImageId();
        }
        YoshopUploadFileEntity file = yoshopUploadFileService.getUploadFileById(imageId);
        // goodsSkuDto.setImageUrl(file.getPreviewUrl());
        // goodsSkuDto.setGoodsImage(file.getPreviewUrl());
        // goodsSkuDto.setSpecValueIds(getSpecValueIds(goodsSku.getGoodsSkuId()));
        goods.setGoodsImage(file.getPreviewUrl());
        goods.setSkuInfo(goodsSkuDto);
        goods.setContent(null);
        return goods;
    }

    @Override
    public QueryStoreGoodsDetail queryStoreGoodsDetailById(Integer goodsId, Integer userId) {
        if (userId == null){
            String cacheKey = "store:goods:detail:" + goodsId;
            if (redisUtils.hasKey(cacheKey)) {
                return (QueryStoreGoodsDetail) redisUtils.get(cacheKey);
            }

            QueryStoreGoodsDetail storeGoodsDetail = new QueryStoreGoodsDetail();
            QueryGoodsDetail goodsDetail = this.queryGoodsDetailById(goodsId);
            if (goodsDetail == null) {
                return null;
            }
            BeanUtils.copyProperties(goodsDetail, storeGoodsDetail);

            List<GoodsSkuDto> skuList = storeGoodsDetail.getSkuList();
            for (GoodsSkuDto goodsSkuDto : skuList) {
                goodsSkuDto.setCreateTime(null);
                goodsSkuDto.setUpdateTime(null);
                goodsSkuDto.setGoodsImage(null);
                goodsSkuDto.setImage(null);
                goodsSkuDto.setStoreId(null);
            }

            // 缓存
            redisUtils.set(cacheKey, storeGoodsDetail, 60 * 60 * 24);

            return storeGoodsDetail;
        }


        String cacheUserKey = "store:goods:detail:" + goodsId+":"+userId;
        if (redisUtils.hasKey(cacheUserKey)) {
            return (QueryStoreGoodsDetail) redisUtils.get(cacheUserKey);
        }

        QueryStoreGoodsDetail storeGoodsDetail = new QueryStoreGoodsDetail();
        QueryGoodsDetail goodsDetail = this.queryGoodsDetailById(goodsId);
        if (goodsDetail == null) {
            return null;
        }
        BeanUtils.copyProperties(goodsDetail, storeGoodsDetail);
        // 获取用户信息
        YoshopUserEntity user = feignStoreClient.queryUserByUserId(userId);
        // 获取用户会员等级
        YoshopUserGradeEntity userGrade = feignStoreClient.queryUserGrade(user.getGradeId());
        if (userGrade != null) {
            storeGoodsDetail.setIsUserGrade(true);
            // 会员折扣比例
            String equity = userGrade.getEquity();
            Map map = JSON.parseObject(equity, Map.class);
            String gradeRatio = (String) map.get("discount");   // 9.7折
            // 会员折扣价格（原价*97%=现价）
            BigDecimal goodsPriceMin = new BigDecimal(goodsDetail.getGoodsPriceMin());
            BigDecimal goodsPriceMax = new BigDecimal(goodsDetail.getGoodsPriceMax());
            BigDecimal gradePriceMinGoods = goodsPriceMin.multiply(new BigDecimal(gradeRatio)).multiply(new BigDecimal("0.1")).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal gradePriceMaxGoods = goodsPriceMax.multiply(new BigDecimal(gradeRatio)).multiply(new BigDecimal("0.1")).setScale(2, BigDecimal.ROUND_HALF_UP);
            storeGoodsDetail.setGoodsPriceMin(String.valueOf(gradePriceMinGoods));
            storeGoodsDetail.setGoodsPriceMax(String.valueOf(gradePriceMaxGoods));
        }
        List<GoodsSkuDto> skuList = storeGoodsDetail.getSkuList();
        for (GoodsSkuDto goodsSkuDto : skuList) {
            goodsSkuDto.setCreateTime(null);
            goodsSkuDto.setUpdateTime(null);
            goodsSkuDto.setGoodsImage(null);
            goodsSkuDto.setImage(null);
            goodsSkuDto.setStoreId(null);
        }

        // 缓存
        redisUtils.set(cacheUserKey, storeGoodsDetail, 60 * 60 * 24);

        return storeGoodsDetail;
    }

    @Override
    public YoshopGoodsImageEntity queryGoodsImage(Integer goodsId) {
        List<YoshopGoodsImageEntity> goodsImageEntityList = goodsImageService.list(new QueryWrapper<YoshopGoodsImageEntity>().eq("goods_id", goodsId).orderByAsc("create_time"));
        return goodsImageEntityList.get(0);
    }

    @Override
    public Integer queryGoodsStockNum(Integer goodsId, String goodsSkuId) {
        YoshopGoodsSkuEntity goodsSku = goodsSkuService.getOne(new QueryWrapper<YoshopGoodsSkuEntity>()
                .eq("goods_id", goodsId)
                .eq("goods_sku_id", goodsSkuId));
        return goodsSku.getStockNum();
    }

    @Override
    public List<YoshopGoodsEntity> querySaleGoodsList() {
        LambdaQueryWrapper<YoshopGoodsEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YoshopGoodsEntity::getIsDelete, 0).eq(YoshopGoodsEntity::getStatus, 10);
        lqw.orderByDesc(YoshopGoodsEntity::getSalesActual);
        Page<YoshopGoodsEntity> page = this.page(new Page<>(1, 5), lqw);
        return page.getRecords();
    }

    @Override
    public QueryGoodsList queryGoodsDto(int goodsId) {
        // 获取商品page数据
        YoshopGoodsEntity goods = this.getById(goodsId);
        QueryGoodsList queryGoods = new QueryGoodsList();
        BeanUtils.copyProperties(goods, queryGoods);
        this.setGoodsImageAndDatetime(queryGoods);
        queryGoods.setContent(null);
        return queryGoods;
    }

    private List<Integer> getSpecValueIds(String goodsSkuId) {
        List<Integer> valueIds = new ArrayList<>();
        try {
            // 使用 split 方法按下划线分割字符串
            String[] idsArray = goodsSkuId.split("_");

            for (String id : idsArray) {
                // 尝试将字符串转换为整数并添加到集合中
                int num = Integer.parseInt(id);
                valueIds.add(num);
            }
        } catch (NumberFormatException e) {
            // System.out.println("Error: Encountered a non-numeric string.");
            throw new YuanChuException("skuId转换集合异常");
        }
        return valueIds;
    }

    /**
     * 保存商品规格属性信息到表goods_spec
     * 保存商品规格值信息到表goods_spec_value
     * 保存商品规格关系信息到表goods_spec_rel
     *
     * @param goodsParams
     * @param goodsId
     */
    public void saveGoodsToSpec(AddGoodsParamsDto goodsParams, Integer goodsId, int storeId) {
        if (goodsParams.getSpecData() == null) {
            return;
        }
        List<SpecData.SpecList> specList = goodsParams.getSpecData().getSpecList();
        List<SpecData.SkuList> skuList = goodsParams.getSpecData().getSkuList();
        if (CollectionUtils.isEmpty(specList)) {
            return;
        }
        if (CollectionUtils.isEmpty(skuList)) {
            return;
        }
        // 保存规格属性
        specList.forEach(spec -> {
            // 判断规格属性是否存在，存在不保存
            YoshopSpecEntity specEntity = specService.getOne(new QueryWrapper<YoshopSpecEntity>()
                    .eq("spec_name", spec.getSpecName()));
            if (specEntity == null) {
                specEntity = new YoshopSpecEntity();
                specEntity.setSpecName(spec.getSpecName());
                specEntity.setStoreId(storeId);
                specEntity.setCreateTime(System.currentTimeMillis() / 1000);
                // 不存在则保存
                specService.save(specEntity);
            }
            // 保存规格值
            YoshopSpecEntity finalSpecEntity = specEntity;
            List<SpecData.SpecList.ValueList> valueList = spec.getValueList();
            valueList.forEach(value -> {
                // 判断规格值是否存在，存在不保存
                YoshopSpecValueEntity specValueEntity = specValueService.getOne(new QueryWrapper<YoshopSpecValueEntity>()
                        .eq("spec_value", value.getSpecValue()));
                if (specValueEntity == null) {
                    specValueEntity = new YoshopSpecValueEntity();
                    specValueEntity.setSpecId(finalSpecEntity.getSpecId());
                    specValueEntity.setSpecValue(value.getSpecValue());
                    specValueEntity.setStoreId(storeId);
                    specValueEntity.setCreateTime(System.currentTimeMillis() / 1000);
                    // 保存商品规格值表
                    specValueService.save(specValueEntity);
                }
                // 保存商品规格值关系表
                YoshopGoodsSpecRelEntity goodsSpecRel = new YoshopGoodsSpecRelEntity();
                goodsSpecRel.setSpecId(finalSpecEntity.getSpecId());
                goodsSpecRel.setSpecValueId(specValueEntity.getSpecValueId());
                goodsSpecRel.setGoodsId(goodsId);
                goodsSpecRel.setStoreId(storeId);
                goodsSpecRel.setCreateTime(System.currentTimeMillis() / 1000);
                // 保存商品规格值关系表
                goodsSpecRelService.save(goodsSpecRel);
            });
        });
    }

    @Override
    public void saveGoodsToCategory(List<Integer> categoryIds, Integer goodsId, int storeId) {
        categoryIds.forEach(categoryId -> {
            YoshopGoodsCategoryRelEntity goodsCategoryRel = new YoshopGoodsCategoryRelEntity();
            goodsCategoryRel.setGoodsId(goodsId);
            goodsCategoryRel.setCategoryId(categoryId);
            goodsCategoryRel.setStoreId(storeId);
            goodsCategoryRel.setCreateTime(System.currentTimeMillis() / 1000);
            goodsCategoryRelService.save(goodsCategoryRel);
        });
    }

    @Override
    public void saveGoodsToImage(List<Integer> imagesIds, Integer goodsId, int storeId) {
        imagesIds.forEach(imageId -> {
            YoshopGoodsImageEntity goodsImageRel = new YoshopGoodsImageEntity();
            goodsImageRel.setGoodsId(goodsId);
            goodsImageRel.setImageId(imageId);
            goodsImageRel.setStoreId(storeId);
            goodsImageRel.setCreateTime(System.currentTimeMillis() / 1000);
            goodsImageService.save(goodsImageRel);
        });
    }

    @Override
    public void saveGoodsToService(List<Integer> serviceIds, Integer goodsId, int storeId) {
        serviceIds.forEach(serviceId -> {
            YoshopGoodsServiceRelEntity goodsServiceRel = new YoshopGoodsServiceRelEntity();
            goodsServiceRel.setGoodsId(goodsId);
            goodsServiceRel.setServiceId(serviceId);
            goodsServiceRel.setStoreId(storeId);
            goodsServiceRel.setCreateTime(System.currentTimeMillis() / 1000);
            goodsServiceRelService.save(goodsServiceRel);
        });
    }

    @Override
    public QueryGoodsDetail queryGoodsDetailById(Integer goodsId) {


        // 1、查询商品基本信息
        YoshopGoodsEntity goodsEntity = goodsService.getById(goodsId);
        if (goodsEntity == null) {
            return null;
        }
        QueryGoodsDetail goodsDetail = new QueryGoodsDetail();
        BeanUtils.copyProperties(goodsEntity, goodsDetail);
        List<YoshopUploadFileEntity> goodsImages = this.getGoodsImages(goodsEntity.getGoodsId());
        if (!CollectionUtils.isEmpty(goodsImages)) {
            goodsDetail.setGoodsImages(goodsImages);
            goodsDetail.setGoodsImage(goodsImages.get(0).getPreviewUrl());
        }
        // 格式化商品content
        String content = goodsEntity.getContent();
        String content_new = content.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"");
        goodsDetail.setContent(content_new);
        String aloneGradeEquity = goodsEntity.getAloneGradeEquity();
        if (!StringUtils.isEmpty(aloneGradeEquity) && !aloneGradeEquity.equals("[]")) {
            // 将JSON字符串转换为Map对象
            Map<String, Double> map = JSON.parseObject(aloneGradeEquity, new TypeReference<Map<String, Double>>() {
            });
            goodsDetail.setAloneGradeEquity(map);
        }

        goodsDetail.setGoodsPriceMin(goodsEntity.getGoodsPriceMin());
        goodsDetail.setGoodsPriceMax(goodsEntity.getGoodsPriceMax());
        int goodsSales = goodsEntity.getSalesActual() + goodsEntity.getSalesInitial();
        goodsDetail.setGoodsSales(goodsSales);
        List<Integer> categoryIds = goodsCategoryRelService.getGoodsCategoryIds(goodsDetail.getGoodsId());
        goodsDetail.setCategoryIds(categoryIds);
        List<SpecData.SpecList> specList = goodsSpecRelService.getSpecListById(goodsEntity.getGoodsId());
        goodsDetail.setSpecList(specList);
        goodsDetail.setServiceIds(goodsServiceRelService.getServiceIds(goodsDetail.getGoodsId()));
        goodsDetail.setSpecLocked(false);
        goodsDetail.setSkuList(goodsSkuService.getSkuListById(goodsDetail.getGoodsId()));
        goodsDetail.setVideo(yoshopUploadFileService.getUploadFileById(goodsDetail.getVideoId()));
        goodsDetail.setVideoCover(yoshopUploadFileService.getUploadFileById(goodsDetail.getVideoCoverId()));


        return goodsDetail;
    }


    /**
     * 保存商品规格信息到表goods_sku
     *
     * @param goodsParams
     * @param goodsId
     * @param storeId
     */
    public void saveGoodsToSku(AddGoodsParamsDto goodsParams, Integer goodsId, int storeId) {
        // 获取商品sku实体
        // List<YoshopGoodsSpecRelEntity> goodsSpecRelList = goodsSpecRelService.list(new QueryWrapper<YoshopGoodsSpecRelEntity>().eq("goods_id", goodsId));
        // if (CollectionUtils.isEmpty(goodsSpecRelList)) {
        //     return;
        // }
        // List<SpecData.SkuList> skuList = goodsParams.getSpecData().getSkuList();
        // if (CollectionUtils.isEmpty(skuList)) {
        //     return;
        // }
        SpecData specData = goodsParams.getSpecData();
        if (specData == null) {
            YoshopGoodsSkuEntity skuEntity = new YoshopGoodsSkuEntity();
            skuEntity.setGoodsId(goodsId);
            skuEntity.setStoreId(storeId);
            skuEntity.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
            skuEntity.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));
            skuEntity.setGoodsPrice(goodsParams.getGoodsPrice());
            skuEntity.setLinePrice(goodsParams.getLinePrice());
            skuEntity.setStockNum(goodsParams.getStockNum());
            skuEntity.setGoodsWeight(Double.valueOf(goodsParams.getGoodsWeight()));
            // 保存sku至数据库
            goodsSkuService.save(skuEntity);
            return;
        }
        List<SpecData.SkuList> skuList = specData.getSkuList();
        skuList.forEach(sku -> {
            YoshopGoodsSkuEntity skuEntity = new YoshopGoodsSkuEntity();
            skuEntity.setGoodsId(goodsId);
            skuEntity.setStoreId(storeId);
            skuEntity.setGoodsSkuNo(sku.getGoodsSkuNo());
            skuEntity.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
            skuEntity.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));
            YoshopSpecValueEntity specValue0 = specValueService.getSpecValueId(sku.getSpecValue0());
            YoshopSpecValueEntity specValue1 = specValueService.getSpecValueId(sku.getSpecValue1());
            YoshopSpecValueEntity specValue2 = specValueService.getSpecValueId(sku.getSpecValue2());
            // 商品sku唯一标识 (由规格id组成)
            String goodsSkuId = "";
            // 规格值ID集(json格式)
            ArrayList<Object> goodsSkuValueIds = new ArrayList<>();
            // SKU的规格属性(json格式)
            List<Map<String, Map<String, Object>>> goodsSkuProps = new ArrayList<>();
            if (specValue0 != null) {
                goodsSkuId = String.valueOf(specValue0.getSpecValueId());
                goodsSkuValueIds.add(specValue0.getSpecValueId());
                Map<String, Map<String, Object>> props = getGoodsProps(sku.getSpecValue0(), specValue0);
                goodsSkuProps.add(props);
            }
            if (specValue1 != null) {
                goodsSkuId = goodsSkuId + "_" + specValue1.getSpecValueId();
                goodsSkuValueIds.add(specValue1.getSpecValueId());
                Map<String, Map<String, Object>> props = getGoodsProps(sku.getSpecValue1(), specValue1);
                goodsSkuProps.add(props);
            }
            if (specValue2 != null) {
                goodsSkuId = goodsSkuId + "_" + specValue2.getSpecValueId();
                goodsSkuValueIds.add(String.valueOf(specValue2.getSpecValueId()));
                Map<String, Map<String, Object>> props = getGoodsProps(sku.getSpecValue2(), specValue2);
                goodsSkuProps.add(props);
            }
            skuEntity.setGoodsSkuId(goodsSkuId);
            skuEntity.setImageId(sku.getImageId());
            skuEntity.setGoodsPrice(String.valueOf(sku.getGoodsPrice()));
            skuEntity.setLinePrice(String.valueOf(sku.getLinePrice()));
            skuEntity.setStockNum(sku.getStockNum());
            skuEntity.setGoodsWeight(sku.getGoodsWeight());
            // SKU的规格属性(json格式)
            skuEntity.setGoodsProps(JSON.toJSONString(goodsSkuProps));
            // 规格值ID集(json格式)
            skuEntity.setSpecValueIds(JSON.toJSONString(goodsSkuValueIds));
            // 保存sku至数据库
            goodsSkuService.save(skuEntity);
        });

    }

    /**
     * 获取商品规格属性
     *
     * @param sku
     * @param specValue
     * @return
     */
    private Map<String, Map<String, Object>> getGoodsProps(String sku, YoshopSpecValueEntity specValue) {
        Map<String, Map<String, Object>> map = new LinkedHashMap<>();
        HashMap<String, Object> groupMap = new HashMap<>();
        groupMap.put("name", getSpecName(specValue.getSpecId()));
        groupMap.put("id", specValue.getSpecId());
        map.put("group", groupMap);
        HashMap<String, Object> valueMap = new HashMap<>();
        valueMap.put("name", sku);
        valueMap.put("id", specValue.getSpecValueId());
        map.put("value", valueMap);
        return map;
    }

    /**
     * 根据规格ID获取规格名称
     *
     * @param specId
     * @return
     */
    private String getSpecName(Integer specId) {
        return specService.getById(specId).getSpecName();
    }


    public Integer saveGoodsToDb(AddGoodsParamsDto goodsParams, String goodsId, int storeId) {
        YoshopGoodsEntity goodsEntity = new YoshopGoodsEntity();
        BeanUtils.copyProperties(goodsParams, goodsEntity);
        SpecData specData = goodsParams.getSpecData();
        // 格式化商品content
        String content = goodsParams.getContent();
        String content_new = content.replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
        goodsEntity.setContent(content_new);
        if (specData == null) {
            goodsEntity.setGoodsPriceMax(goodsParams.getGoodsPrice());
            goodsEntity.setGoodsPriceMin(goodsParams.getGoodsPrice());
            goodsEntity.setLinePriceMax(goodsParams.getGoodsPrice());
            goodsEntity.setLinePriceMin(goodsParams.getGoodsPrice());
            goodsEntity.setStockTotal(goodsParams.getStockNum());
        } else {
            List<SpecData.SkuList> skuList = specData.getSkuList();
            // 获取商品价格最大值
            OptionalDouble max = skuList.stream()
                    .mapToDouble(SpecData.SkuList::getGoodsPrice).max();
            if (max.isPresent()) {
                goodsEntity.setGoodsPriceMax(String.valueOf(max.getAsDouble()));
            }
            // 获取商品价格最小值
            OptionalDouble min = skuList.stream()
                    .mapToDouble(SpecData.SkuList::getGoodsPrice).min();
            if (min.isPresent()) {
                goodsEntity.setGoodsPriceMin(String.valueOf(max.getAsDouble()));
            }
            // 获取划线商品价格最大值
            OptionalDouble lineMax = skuList.stream()
                    .mapToDouble(SpecData.SkuList::getLinePrice).max();
            if (lineMax.isPresent()) {
                goodsEntity.setLinePriceMax(String.valueOf(lineMax.getAsDouble()));
            }
            // 获取划线商品价格最小值
            OptionalDouble lineMin = skuList.stream()
                    .mapToDouble(SpecData.SkuList::getLinePrice).min();
            if (lineMin.isPresent()) {
                goodsEntity.setLinePriceMin(String.valueOf(lineMin.getAsDouble()));
            }
            // 获取库存总数
            int sum = skuList.stream().mapToInt(SpecData.SkuList::getStockNum).sum();
            goodsEntity.setStockTotal(sum);
        }
        // 商城id  10001
        goodsEntity.setStoreId(storeId);
        // 创建时间
        goodsEntity.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
        // 修改时间
        goodsEntity.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));

        // 是否开启会员折扣（1开启0关闭）
        if (goodsParams.getIsEnableGrade() == 1) {
            // 是否是默认等级折扣
            if (goodsParams.getIsAloneGrade() == 0) {
                // 默认等级折扣
                goodsEntity.setAloneGradeEquity("[]");
            } else {
                // 单独设置折扣的配置
                Map<String, Double> aloneEquity = new HashMap<>();
                goodsParams.getAloneGradeEquity().forEach((k, v) -> {
                    int index = k.indexOf(":") + 1;
                    String result = k.substring(index);
                    aloneEquity.put(result, v);
                });
                String jsonString = JSON.toJSONString(aloneEquity);
                goodsEntity.setAloneGradeEquity(jsonString);
            }
        }

        if (StringUtils.isNotBlank(goodsId)) {
            goodsEntity.setGoodsId(Integer.valueOf(goodsId));
            // this.updateById(goodsEntity);
        }
        //  保存至商品数据库
        this.saveOrUpdate(goodsEntity);
        return goodsEntity.getGoodsId();
    }

    /**
     * 根据商品id获取商品图片
     *
     * @param goodsId 商品id
     * @return
     */
    public List<YoshopUploadFileEntity> getGoodsImages(Integer goodsId) {
        LambdaQueryWrapper<YoshopGoodsImageEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YoshopGoodsImageEntity::getGoodsId, goodsId);
        lqw.orderByAsc(YoshopGoodsImageEntity::getCreateTime);
        List<YoshopGoodsImageEntity> imageIds = goodsImageService.list(lqw);
        if (CollectionUtils.isEmpty(imageIds)) {
            return Collections.emptyList();
        }
        List<Integer> ids = imageIds.stream().map(YoshopGoodsImageEntity::getImageId).collect(Collectors.toList());
        LambdaQueryWrapper<YoshopUploadFileEntity> lqw2 = new LambdaQueryWrapper<>();
        lqw2.in(YoshopUploadFileEntity::getFileId, ids);

        List<YoshopUploadFileEntity> list = fileService.list(lqw2);
        return list.stream().map(FormatUtils::formatFile).collect(Collectors.toList());
    }

}













